package com.yonyong.tao.service;

import com.yonyong.tao.mapper.dbone.TblDepartmentMapper;
import com.yonyong.tao.mapper.dbone.TblDeviceMapper;
import com.yonyong.tao.mapper.dbone.TblEmployeeMapper;
import com.yonyong.tao.mapper.local.TblDepartmentsMapper;
import com.yonyong.tao.mapper.local.TblDeviceInfoMapper;
import com.yonyong.tao.mapper.local.TblEmployeesMapper;
import com.yonyong.tao.model.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Describtion Todo
 * @Author yonyong
 * @Date 2020/3/28 12:32
 * @Version 1.0.0
 **/
@Service
//@Transactional(rollbackFor = Exception.class)
@Slf4j
public class RunnerOneService {

    private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    TblDepartmentsMapper localDepartmentMapper;
    @Resource
    TblDepartmentMapper tblDepartmentMapper;
    @Resource
    TblEmployeesMapper localEmployeesMapper;
    @Resource
    TblEmployeeMapper tblEmployeeMapper;
    @Resource
    TblDeviceInfoMapper localDeviceMapper;
    @Resource
    TblDeviceMapper tblDeviceMapper;


    public void runEmployee(){
        AffectRow e = updateEmployee();
        if (e.getTotal() != 0){
            log.info(MessageFormat.format("本次执行结果：employees表：{0}条（其中update{1}条，add{2}条）；",e.getTotal(),e.getUpdate(),e.getAdd()));
        }
    }

    public void runDepartment(){
        AffectRow dp = updateDepartment();
        if (dp.getTotal() != 0){
            log.info(MessageFormat.format(
                    "本次执行结果：departments表：{0}条（其中update{1}条，add{2}条）；",dp.getTotal(),dp.getUpdate(),dp.getAdd()));
        }
    }

    public void runDevice(){
        AffectRow de = updateDevice();
        if (de.getTotal() != 0){
            log.info(MessageFormat.format(
                    "本次执行结果：device_info表：{0}条（其中update{1}条，add{2}条）；",de.getTotal(),de.getUpdate(),de.getAdd()));
        }
    }


    /**
     * 执行
     */

//    public void run(){
//        System.out.println("no device");
//        AffectRow e = updateEmployee();
//        AffectRow dp = updateDepartment();
//        if (e.getTotal() != 0){
//            log.info(MessageFormat.format("本次执行结果：employees表：{0}条（其中update{1}条，add{2}条）；",e.getTotal(),e.getUpdate(),e.getAdd()));
//        }
//        if (dp.getTotal() != 0){
//            log.info(MessageFormat.format(
//                    "本次执行结果：departments表：{0}条（其中update{1}条，add{2}条）；",dp.getTotal(),dp.getUpdate(),dp.getAdd()));
//        }
//    }

    private AffectRow updateEmployee()   {
//        Date employeeDate = DATE_FORMAT.parse(localEmployeesMapper.getTime());
        String employeeDate = localEmployeesMapper.getTime();
        String employeeCreateDate = localEmployeesMapper.getCreateTime();
        Example example = new Example(TblEmployee.class);
        example.createCriteria().andCondition("MODIFY_DATE > '"+employeeDate +"' or CREATE_DATE > '"+ employeeCreateDate + "'");
        List<TblEmployee> list = tblEmployeeMapper.selectByExample(example);
//        log.info(MessageFormat.format("{0}获取数据:{1}条，其中创建时间大于：{2}，修改时间大于：{3}",
//                "updateEmployee",list.size(),employeeCreateDate,employeeDate));
        int add = 0;
        int update = 0;
        for (TblEmployee source:list) {
            String flag = source.getUsername();
            Example example1 = new Example(TblEmployees.class);
            example1.createCriteria().andEqualTo("username",flag);
            List<TblEmployees> list1 = localEmployeesMapper.selectByExample(example1);
            if (null != list1 && list1.size()>0){
                //如果已有记录
                for (TblEmployees temp: list1){
                    temp.setRealusername(source.getName());
                    temp.setPhonenum(source.getUsername());
                    temp.setDepartcode(source.getDepartCode());
                    temp.setIsDeleted(source.getIsDeleted());
                    temp.setCcbEmployeeNum(source.getPoliceNo());
                    temp.setIdentityCard(source.getIdCard());
                    temp.setCreator(source.getCreator());
                    temp.setModifier(source.getModifier());
                    temp.setRawUpdatetime(source.getModifyDate());
                    temp.setRawAddtime(source.getCreateDate());
                    try{
                        localEmployeesMapper.updateByExampleSelective(temp,example1);
                    }catch (Exception e){
                        log.info(MessageFormat.format("更新到第{0}条，报错记录{1}",update++,temp.toString()));
                    }
                    update++;
                }
            }else {
                //没有直接insert
                TblEmployees temp = new TblEmployees();
                //insert时set flag
                temp.setUsername(flag);

                temp.setRealusername(source.getName());
                temp.setPhonenum(source.getUsername());
                temp.setDepartcode(source.getDepartCode());
                temp.setIsDeleted(source.getIsDeleted());
                temp.setCcbEmployeeNum(source.getPoliceNo());
                temp.setIdentityCard(source.getIdCard());
                temp.setCreator(source.getCreator());
                temp.setModifier(source.getModifier());
                temp.setRawUpdatetime(source.getModifyDate());
                temp.setRawAddtime(source.getCreateDate());
                localEmployeesMapper.insertSelective(temp);
                add++;
            }
        }
        AffectRow affectRow = new AffectRow(add,update,add+update);
        return affectRow;
    }

    private AffectRow updateDepartment()   {
//        Date departmentDate = DATE_FORMAT.parse(localDepartmentMapper.getTime());
        String departmentDate = localDepartmentMapper.getTime();
        String departmentCreateDate = localDepartmentMapper.getCreateTime();
        Example example = new Example(TblDepartment.class);
        example.createCriteria().andCondition("MODIFY_DATE > '"+departmentDate +"' or CREATE_DATE > '"+departmentCreateDate + "'");
        List<TblDepartment> list = tblDepartmentMapper.selectByExample(example);
//        log.info(MessageFormat.format("{0}获取数据:{1}条，其中创建时间大于：{2}，修改时间大于：{3}",
//                "updateDepartment",list.size(),departmentCreateDate,departmentDate));
        int add = 0 ;
        int update = 0;
        for (TblDepartment source:list) {
            String flag = source.getDepartCode();
            Example example1 = new Example(TblDepartments.class);
            example1.createCriteria().andEqualTo("departCode",flag);
            List<TblDepartments> list1 = localDepartmentMapper.selectByExample(example1);
            if (null != list1 && list1.size()>0){
                //如果已有记录
                for (TblDepartments temp: list1){
                    temp.setDepartPath(source.getDepartPath());
                    temp.setParentCode(source.getParentCode());
                    temp.setName(source.getName());
                    temp.setLevel(source.getLevel());
                    temp.setLeaf(source.getLeaf());
                    temp.setCreator(source.getCreator());
                    temp.setModifier(source.getModifier());
                    temp.setModifyDate(source.getModifyDate());
                    temp.setCreateDate(source.getCreateDate());
                    temp.setIsDeleted(source.getIsDeleted());
                    localDepartmentMapper.updateByExampleSelective(temp,example1);
                    update++;
                }
            }else {
                //没有直接insert
                TblDepartments temp = new TblDepartments();
                //insert时set flag
                temp.setDepartCode(flag);

                temp.setDepartPath(source.getDepartPath());
                temp.setParentCode(source.getParentCode());
                temp.setName(source.getName());
                temp.setLevel(source.getLevel());
                temp.setLeaf(source.getLeaf());
                temp.setCreator(source.getCreator());
                temp.setModifier(source.getModifier());
                temp.setModifyDate(source.getModifyDate());
                temp.setCreateDate(source.getCreateDate());
                temp.setIsDeleted(source.getIsDeleted());
                localDepartmentMapper.insertSelective(temp);
                add++;
            }
        }
        AffectRow affectRow = new AffectRow(add,update,add+update);
        return affectRow;
    }

    private AffectRow updateDevice()   {
//        Date deviceDate = DATE_FORMAT.parse(localDeviceMapper.getTime());
        String deviceDate = localDeviceMapper.getTime();
        String deviceCreateDate = localDeviceMapper.getCreateTime();
        Example example = new Example(TblDevice.class);
        example.createCriteria().andCondition("MODIFY_DATE > '"+deviceDate +"' or CREATE_DATE > '"+deviceCreateDate + "'");
        List<TblDevice> list = tblDeviceMapper.selectByExample(example);
//        log.info(MessageFormat.format("{0}获取数据:{1}条，其中创建时间大于：{2}，修改时间大于：{3}",
//                "updateDevice",list.size(),deviceCreateDate,deviceDate));
        int add = 0;
        int update = 0;
        for (TblDevice source:list) {
            String flag = source.getIdentifier();
            Example example1 = new Example(TblDeviceInfo.class);
            example1.createCriteria().andEqualTo("deviceidentifier",flag);
            List<TblDeviceInfo> list1 = localDeviceMapper.selectByExample(example1);
            if (null != list1 && list1.size()>0){
                //如果已有记录
                for (TblDeviceInfo temp: list1){
                    temp.setDeviceName(source.getName());
                    temp.setOsVersion(source.getOsVersion());
                    temp.setDeviceStatus(source.getStatus());
                    temp.setUsername(source.getUsername());
                    temp.setDepartCode(source.getDepartCode());
                    temp.setCreator(source.getCreator());
                    temp.setModifier(source.getModifier());
                    temp.setRawUpdatetime(source.getModifyDate());
                    temp.setRawAddtime(source.getCreateDate());
                    temp.setIsDeleted(source.getIsDeleted());
                    temp.setImei(source.getImei());
                    localDeviceMapper.updateByExampleSelective(temp,example1);
                    update++;
                }
            }else {
                //没有直接insert
                TblDeviceInfo temp = new TblDeviceInfo();
                //insert时set flag
                temp.setDeviceidentifier(flag);

                temp.setDeviceName(source.getName());
                temp.setOsVersion(source.getOsVersion());
                temp.setDeviceStatus(source.getStatus());
                temp.setUsername(source.getUsername());
                temp.setDepartCode(source.getDepartCode());
                temp.setCreator(source.getCreator());
                temp.setModifier(source.getModifier());
                temp.setRawUpdatetime(source.getModifyDate());
                temp.setRawAddtime(source.getCreateDate());
                temp.setIsDeleted(source.getIsDeleted());
                temp.setImei(source.getImei());
                localDeviceMapper.insertSelective(temp);
                add++;
            }
        }
        AffectRow affectRow = new AffectRow(add,update,add+update);
        return affectRow;
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class AffectRow{
    private int add;
    private int update;
    private int total;
}
